package com.frank.leetcode.question_11_15;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * https://leetcode-cn.com/problems/longest-common-prefix/description/
 * 14. 最长公共前缀
 * 难度: 简单
 * <p>
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * <p>
 * 如果不存在公共前缀，返回空字符串 ""。
 * <p>
 * 示例 1:
 * <p>
 * 输入: ["flower","flow","flight"]
 * 输出: "fl"
 * 示例 2:
 * <p>
 * 输入: ["dog","racecar","car"]
 * 输出: ""
 * 解释: 输入不存在公共前缀。
 * 说明:
 * <p>
 * 所有输入只包含小写字母 a-z 。
 * <p>
 * Created by zhy on 2018/8/2.
 */
public class LongestCommonPrefix {
    private static Logger LOG = LoggerFactory.getLogger(LongestCommonPrefix.class);

    @Test
    public void run() {
        String[] strs = {"aac","cab","abb"};
        System.out.println(longestCommonPrefix(strs));
    }

    private String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) return "";
        if (strs.length == 1) return strs[0];


        char[] s = strs[0].toCharArray();
        int end = s.length;

        for (int i = 1; i < strs.length; i++) {
            if (strs[i].length() < end) {
                end = strs[i].length();
            }
            for (int j = 0; j < Math.min(strs[i].length(), end); j++) {
                if (strs[i].charAt(j) != s[j]) {
                    end = j;
                    break;
                }
            }
        }


        return strs[0].substring(0, end);
    }

}